package org.ch02.job.test13;


import javax.persistence.Column;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.Map;

import static org.ch02.job.test13.SqlGenerate.convertToSnake;

/**
 * @author XCH
 * @date 2025 - 03 - 20
 */
public class DbUtil {
    // 定义数据库连接URL
    private static final String URL = "jdbc:mysql://localhost:3306/jdbc_test?serverTimezone=UTC&useSSL=false&characterEncoding=utf8";


    // 定义数据库驱动类
    private static final String driver = "com.mysql.cj.jdbc.Driver";

    // 定义数据库用户
    private static final String username = "root";

    // 定义数据库密码
    private static final String password = "root";
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("数据库驱动加载失败", e);
        }
    }

    public static Object select4Bean(Class<?> beanClass, Map<String,Object> cond) throws Exception {
        String sql = SqlGenerate.generateSelect(beanClass, cond);
        System.out.println(sql);
        return queryDatabase(sql, cond);
    }

    private static Object queryDatabase(String sql, Map<String, Object> cond) {
        try (Connection conn = DriverManager.getConnection(URL, username, password);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 替换 SQL 中的 ? 为实际参数值
            String fullSql = sql;
            int index = 1;
            for (Map.Entry<String, Object> entry : cond.entrySet()) {
                Object value = entry.getValue();
                stmt.setObject(index++, value);
                int paramIndex = fullSql.indexOf("?");
                if (paramIndex != -1) {
                    String replacement = value instanceof String ? "'" + value + "'" : value.toString();
                    fullSql = fullSql.substring(0, paramIndex) + replacement + fullSql.substring(paramIndex + 1);
                }
            }

            ResultSet resultSet = stmt.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                System.out.println("列名: " + metaData.getColumnName(i));
            }
            if (resultSet.next()) {
                Class<?> clazz = Staff.class;
                Object obj = clazz.getDeclaredConstructor().newInstance();
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();

                    Column column = field.getAnnotation(Column.class);
                    String columnName = column != null ? column.name() : convertToSnake(fieldName);

                    Object value = resultSet.getObject(columnName);

                    if (value == null && field.getType().isPrimitive()) {
                        value = getDefaultValueForPrimitiveType(field.getType());
                    }
                    field.set(obj, value);
                }

                return obj;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    // 处理null并获取基本数据类型的默认值
    private static Object getDefaultValueForPrimitiveType(Class<?> type) {
        if (type == int.class) {
            return 0;
        } else if (type == long.class) {
            return 0L;
        } else if (type == double.class) {
            return 0.0;
        } else if (type == float.class) {
            return 0.0f;
        } else if (type == boolean.class) {
            return false;
        } else if (type == short.class) {
            return (short) 0;
        } else if (type == byte.class) {
            return (byte) 0;
        } else if (type == char.class) {
            return '\u0000';
        }
        return null;
    }
}
